<template>
  <div :style="style" class="vux-flexbox-item">
    <slot/>
  </div>
</template>


<script setup>
import {computed, inject, onBeforeMount, ref} from "vue";

const prefixList = ['-moz-box-', '-webkit-box-', '']

// 使用provide和inject来替代$parent
const parentGutter = inject('parentGutter')
const parentOrient = inject('parentOrient')

defineOptions({
  name: 'FlexboxItem',
})

const props = defineProps({
  span: [Number, String],
  order: [Number, String]
})

const bodyWidth = ref(0)


const style = computed(() => {
  const styles = {}
  const marginName =
      parentOrient === 'horizontal' ? 'marginLeft' : 'marginTop'
  // this.$parent.orient === 'horizontal' ? 'marginLeft' : 'marginTop'

  // if (this.$parent.gutter * 1 !== 0){
  //   styles[marginName] = `${this.$parent.gutter}px`
  // }
  if (parentGutter * 1 !== 0) {
    styles[marginName] = `${parentGutter}px`
  }

  if (props.span) {
    for (let i = 0; i < prefixList.length; i++) {
      styles[`${prefixList[i]}flex`] = `0 0 ${buildWidth(props.span) *
      100}%`
    }
  }
  if (typeof props.order !== 'undefined') {
    styles.order = props.order
  }
  return styles
})

onBeforeMount(() => {
  bodyWidth.value = document.documentElement.offsetWidth
})


const buildWidth = (width) => {
  if (typeof width === 'number') {
    if (width < 1) {
      return width
    } else {
      return width / 12
    }
  } else if (typeof width === 'string') {
    return width.replace('px', '') / bodyWidth.value
  }
}
</script>
